<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
      class="form-search"
    >
      <el-form-item label="任务模板名称" prop="templateName">
        <el-input
          v-model="queryParams.templateName"
          placeholder="请输入任务模板名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="表单名称" prop="reportName">
        <el-input
          v-model="queryParams.reportName"
          placeholder="请输入表单名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="templateType">
        <el-select v-model="queryParams.templateType" placeholder="类型" clearable>
          <el-option
            v-for="dict in task_template_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable>
          <el-option
            v-for="dict in task_template_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
        <el-button icon="refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="plus"
          @click="handleAdd"
          v-hasPermi="['technology/taskTemplate/add']"
        >
          新增
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['technology:processRoute:remove']"
            >删除</el-button
          >
        </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="processRouteList"
      :max-height="500"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column
          label="工艺路线编号"
          align="center"
          prop="processRouteNo"
        /> -->
      <el-table-column label="任务模板编号" prop="templateCode">
        <template #default="scope">
          <el-link type="primary" @click="view(scope.row)">
            {{ scope.row.templateCode }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="任务模板名称" align="center" prop="templateName" />
      <el-table-column label="模板类型" align="center" prop="templateType">
        <template #default="scope">
          <dict-tag :options="task_template_type" :value="scope.row.templateType" />
        </template>
      </el-table-column>
      <el-table-column label="版本号" align="center" prop="version" />

      <el-table-column label="报表名称" align="center" prop="reportName" />

      <el-table-column label="更新时间" align="center" prop="updateTime" />

      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="task_template_status" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="160"
      >
        <template #default="scope">
          <el-button
            link
            icon="edit"
            type="primary"
            v-if="scope.row.status == 'TASK_TEMPLATE_STATUS_WAIT_ENABLE'"
            @click="enable(scope.row)"
            v-hasPermi="['technology/taskTemplate/enabel']"
          >
            启用
          </el-button>
          <el-button
            link
            icon="edit"
            type="primary"
            v-if="scope.row.status == 'TASK_TEMPLATE_STATUS_ENABLE'"
            @click="stop(scope.row)"
            v-hasPermi="['technology/taskTemplate/stop']"
          >
            停用
          </el-button>
          <el-button
            link
            icon="edit"
            type="primary"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.status == 'TASK_TEMPLATE_STATUS_WAIT_ENABLE'"
            v-hasPermi="['technology:processRoute:edit']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            icon="edit"
            v-if="scope.row.status == 'TASK_TEMPLATE_STATUS_ENABLE'"
            @click="handleUpgrade(scope.row)"
            v-hasPermi="['technology:processRoute:addVersion']"
          >
            升级版本
          </el-button>
          <el-button
            link
            icon="delete"
            type="primary"
            v-if="scope.row.status == 'TASK_TEMPLATE_STATUS_WAIT_ENABLE'"
            @click="handleDelete(scope.row)"
            v-hasPermi="['technology:processRoute:remove']"
          >
            删除
          </el-button>
          <el-button
            link
            icon="delete"
            type="primary"
            @click="copy(scope.row)"
            v-hasPermi="['technology:processRoute:copy']"
          >
            复制
          </el-button>
          <el-button
            link
            icon="delete"
            type="primary"
            @click="preview(scope.row)"
            v-hasPermi="['technology:processRoute:preview']"
          >
            预览
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 升级版本 -->
    <el-dialog
      :close-on-click-modal="false"
      v-model="dialogFormVisible"
      title="升级版本"
      width="600"
    >
      <el-form-item label="新版本" prop="version">
        <el-input v-model="upgradeForm.version" />
      </el-form-item>
      <p style="color: red">
        注意：待新版本启用后，将自动停用旧版本，同时旧版本在工艺流程中的应用也将自动更换为新版本
      </p>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmUpgrade">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 复制 -->
    <el-dialog
      :close-on-click-modal="false"
      v-model="dialogFormVisibleCopy"
      title="复制任务模板"
      width="600"
    >
      <el-form-item label="*任务模板名称" prop="version">
        <el-input v-model="upgradeFormCopy.templateName" />
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisibleCopy = false">取 消</el-button>
          <el-button type="primary" @click="confirmUpgradeCopy">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 停用 -->
    <el-dialog
      :close-on-click-modal="false"
      v-model="dialogFormVisibleStop"
      title="停用任务模板"
      width="1200"
    >
      <div>
        <p>确定停用 {{ upgradeFormStop.templateName }} 吗？</p>
        <p>停用后次日及之后的任务将不再生成。</p>
        <el-table :data="upgradeFormStopTableData" style="width: 100%">
          <el-table-column prop="processCode" label="工艺编号" width="180" />
          <el-table-column prop="processName" label="产品编号" width="180" />
          <el-table-column prop="productName" label="产品名称" />
          <el-table-column prop="productSort" label="产品分类" />
          <el-table-column prop="factoryAffiliation" label="所属工厂" />
          <el-table-column prop="version" label="版本" />
          <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="tech_process_manage_status" :value="scope.row.status" />
        </template>
      </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisibleStop = false">取 消</el-button>
          <el-button type="primary" @click="confirmUpgradeStop">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ProcessRoute">
import { listProcessRoute, getProcessRoute, delProcessRoute } from "@/api/technology/processRoute";
import jimuReportView from "../../jimureport/view.vue";
import {
  listTaskTemplate,
  delTaskTemplate,
  copyTaskTemplate,
  enableTaskTemplate,
  stopTaskTemplate,
  addVersionTaskTemplate,
  processManageList
} from "@/api/technology/taskTemplate";
import { ref, reactive, getCurrentInstance, toRefs } from "vue";
import addData from "./add.vue";
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const processRouteNos = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const disabledForm = ref(false);
const addVersion = ref("");
// 工艺路线表格数据
const processRouteList = ref([]);
const dialogFormVisible = ref(false);
const dialogFormVisibleCopy = ref(false);
const dialogFormVisibleStop = ref(false);
const upgradeFormStopTableData = ref([]);
const data = reactive({
  form: {},
  upgradeForm: {},
  upgradeFormCopy: {},
  upgradeFormStop: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    processRouteNo: null,
    processRouteName: null,
    factoryCode: null,
    factoryName: null,
    workshopSectionCode: null,
    workshopSectionName: null,
    productLinesCode: null,
    productLinesName: null,
    processSectionCode: null,
    processSectionName: null,
  },
  rules: {
    version: [{ required: true, message: "版本不能为空", trigger: "blur" }],
    name: [{ required: true, message: "任务模板名称不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, upgradeForm, upgradeFormCopy, upgradeFormStop } = toRefs(data);
const { proxy } = getCurrentInstance();
const { task_template_status } = proxy.useDict("task_template_status");
const { tech_process_manage_status } = proxy.useDict("tech_process_manage_status");
const { task_template_type } = proxy.useDict("task_template_type");
import { getToken } from "@/utils/auth";
/** 查询工艺路线列表 */
function getList() {
  loading.value = true;
  listTaskTemplate(queryParams.value).then((response) => {
    processRouteList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 表单重置
function reset() {
  form.value = {
    processRouteNo: null,
    processRouteName: null,
    factoryCode: null,
    factoryName: null,
    workshopSectionCode: null,
    workshopSectionName: null,
    productLinesCode: null,
    productLinesName: null,
    processSectionCode: null,
    processSectionName: null,
    craftCode: null,
    craftName: null,
    productCode: null,
    productName: null,

    remark: null,
  };
  proxy.resetForm("formRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 升级版本 */
function handleUpgrade(row) {
  dialogFormVisible.value = true;
  listTaskTemplate({
    pageNum: 1,
    pageSize: 10000,
    templateCode: row.templateCode,
  }).then((response) => {
    let latestVersion = "v1.0";
    if (response.rows && response.rows.length) {
      latestVersion = response.rows[response.rows.length - 1].version || "v1.0";
    }
    const index = latestVersion.indexOf(".");
    const pre = latestVersion.substring(0, index + 1);
    const currentNum = latestVersion.substring(index + 1, index + 2);
    dialogFormVisible.value = true;
    upgradeForm.value.version =
      pre + (Number(currentNum) || currentNum == 0 ? Number(currentNum) + 1 : 0);
    upgradeForm.value.id = row.id;
  });
}
// 确定升级版本
function confirmUpgrade() {
  if (!upgradeForm.value.version) {
    return proxy.$modal.msgError("请填写新版本号");
  }
  addVersionTaskTemplate(upgradeForm.value).then(() => {
    proxy.$modal.msgSuccess("升级版本成功");
    dialogFormVisible.value = false;
    getList();
  });
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryForm");
  handleQuery();
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  processRouteNos.value = selection.map((item) => item.processRouteNo);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}
/** 新增按钮操作 */
function handleAdd() {
  proxy.subPage(addData, { title: "新增任务模板", data: {  } }, () => {
    getList();
  });
}
// 停用
function stop(row) {
  upgradeFormStop.value = JSON.parse(JSON.stringify(row));
  dialogFormVisibleStop.value = true;
  processManageList(row.id).then((res) => {
    upgradeFormStopTableData.value = res.data
  });
}
// 确定停用
function confirmUpgradeStop() {
  stopTaskTemplate(upgradeFormStop.value.id).then(() => {
    proxy.$modal.msgSuccess("停用成功");
    dialogFormVisibleStop.value = false;
    getList();
  });
}
// 启用
function enable(row) {
  enableTaskTemplate(row.id).then(() => {
    proxy.$modal.msgSuccess("启用成功");
    getList();
  });
}
// 复制
function copy(row) {
  upgradeFormCopy.value = JSON.parse(JSON.stringify(row));
  upgradeFormCopy.value.templateName = "";
  upgradeFormCopy.value.templateCode = "";
  dialogFormVisibleCopy.value = true;
}
// 确定复制
function confirmUpgradeCopy() {
  if (!upgradeFormCopy.value.templateName) {
    return proxy.$modal.msgError("请填写任务模板名称");
  }
  copyTaskTemplate(upgradeFormCopy.value).then(() => {
    proxy.$modal.msgSuccess("复制成功");
    dialogFormVisibleCopy.value = false;
    getList();
  });
}
// 详情
function view(row){
  proxy.subPage(addData, { title: "任务模板详情", data: row ,type:'view'}, () => {
    getList();
  });
}
// 预览
function preview(row){
  const id = row.id 
  // let url = ''
  // if (location.hostname == 'localhost' || location.hostname.indexOf('10.54.48.104')>-1) {
  //   url = 'http://et-mes-ui-resolinkpoc2023-et-mes.crsems.crcloud.com/report/jmreport/index/'+id+'?token='+getToken()
  // } else {
  //   url = "http://" + location.hostname + "/report/jmreport/index"+id+"?token=" + getToken();
  // }
  
  proxy.subPage(jimuReportView, { title: "表单预览", reportID:id,type:'view'}, () => {
    getList();
  });
  // window.open(url)
}
/** 修改按钮操作 */
function handleUpdate(row) {
    proxy.subPage(addData, { title: "编辑任务模板", data: row }, () => {
    getList();
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const idList = row.id || ids.value;
  let msg = "";
  if (row.processRouteNo) {
    msg = `是否确认删除任务模板编号为"${row.templateCode}"数据项？`;
  } else {
    msg = `是否确认删除所选数据项？`;
  }
  proxy.$modal
    .confirm(msg)
    .then(function () {
      return delTaskTemplate(idList);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch((e) => {
      console.log(e);
    });
}
getList();
</script>
